package com.example.hotHub.service.impl;


import com.example.hotHub.model.NormalHotSearch;
import com.example.hotHub.service.BaiduHotPointService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BaiduHotPointServiceImpl implements BaiduHotPointService {

    @Autowired
    private ExecutorService threadPoolExecutor;

    private String getBaiduImage(String url) {
        try {
            Document document = Jsoup.connect(url).get();
            Elements element = document.select("[tabindex=0]").get(0)
                    .select("img");
            String imageUrl = element.select("img").get(0).attr("src");

            return imageUrl;

        } catch (Exception e) {
            log.error("获取百度图片失败: {}", url, e);
        }
        return null;
    }

    @SneakyThrows
    @Override
    public List<NormalHotSearch> getHotPointList() {

        try {
            List<NormalHotSearch> normalHotSearchList = new CopyOnWriteArrayList<>();

            Document document = Jsoup.connect("https://top.baidu.com/board?tab=realtime").get();
            Elements elements = document.getElementsByClass("category-wrap_iQLoo horizontal_1eKyQ");

            int size = elements.size();
            CountDownLatch latch = new CountDownLatch(size);

            for (Element element : elements) {
                threadPoolExecutor.execute(() -> {
                    try {
//                        log.info("获取百度热搜封面, 处理线程: {}", Thread.currentThread().getName());
                        String hotValue = element.getElementsByClass("hot-index_1Bl1a").get(0).text();
                        String title = element.getElementsByClass("c-single-text-ellipsis").get(0).text();
                        String url = element.getElementsByClass("title_dIF3B ").get(0).attr("href");
                        String imageUrl = null;
                        try {
                            imageUrl = element.getElementsByClass("img-wrapper_29V76").get(0).select("img").get(0).attr("src");
                            if (!imageUrl.startsWith("https")) {
                                imageUrl = element.getElementsByClass("img-wrapper_29V76").get(0).select("img").get(1).attr("src");
                            }
                        } catch (Exception ex) {
                            log.error("获取百度热搜: <{}> 封面图片失败", title);
                        }
                        String describe = null;
                        try {
                            describe = element.getElementsByClass("hot-desc_1m_jR large_nSuFU ").get(0).text();
                        } catch (Exception ex) {
                            describe = title;
                            log.error("获取百度热搜: <{}> 描述失败", title);
                        }
                        NormalHotSearch normalHotSearch = new NormalHotSearch()
                                .setTitle(title)
                                .setUrl(url)
                                .setHotValue(StringUtils.hasLength(hotValue) ? Integer.parseInt(hotValue) : null)
                                .setHotValueUnit("")
                                .setDescribe(describe)
                                .setImageUrl(imageUrl);

                        normalHotSearchList.add(normalHotSearch);
                    } catch (Exception ex) {
                        log.error("爬取图片失败: {}", ex);
                    } finally {
                        latch.countDown();
                    }
                });
            }

            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            List<NormalHotSearch> finalNormalHotSearchList = normalHotSearchList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

            log.debug("成功爬取百度热点: {}", finalNormalHotSearchList);


            return finalNormalHotSearchList;
        } catch (IOException e) {
            log.error("爬取百度热点失败", e);
        }

        return null;
    }

}
